package com.zbs.framework.swagger.utils.logs;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zbs.framework.swagger.annotations.ApiOperation;
import com.zbs.framework.swagger.config.SwaggerPropertySetting;
import com.zbs.framework.swagger.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Aspect
@Component
@Order(3)
@EnableAspectJAutoProxy
@EnableAsync
@Slf4j
public class SwaggerLogBaseAspect implements IBaseAspect {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.zbs.framework.swagger.annotations.ApiOperation)")
    public void logPointCut() {
    }


    @Override
    public void before(JoinPoint joinPoint) throws Throwable {
    }

    @Override
    public void after(JoinPoint joinPoint) throws Throwable {

    }

    /**
     * 后置通知，拦截
     *
     * @param joinPoint
     * @param returnObj
     * @throws Throwable
     */
    @Override
    @AfterReturning(pointcut = "logPointCut()", argNames = "joinPoint,returnObj", returning = "returnObj")
    public void afterReturning(JoinPoint joinPoint, Object returnObj) throws Throwable {
        handleLog(joinPoint, null);
    }

    /**
     * 异常拦截操作
     *
     * @param joinPoint
     * @param e
     * @throws Throwable
     */
    @Override
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) throws Throwable {
        handleLog(joinPoint, e);
    }

    /**
     * @param pJoinPoint
     * @return
     * @throws Throwable
     * @Around 可以更改系统返回值
     */
    @Override
    public Object around(ProceedingJoinPoint pJoinPoint) throws Throwable {
        return null;
    }


    protected void handleLog(final JoinPoint joinPoint, final Throwable e) {
        try {
            // 获取注解
            ApiOperation controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            String userName = "";
            // *========数据库日志=========*//
            SysOperateLog operateLog = new SysOperateLog();
            operateLog.setStatus(Boolean.TRUE);

            operateLog.setOperIp(IPAddressUtils.getIpAddr(ServletUtils.getRequest()));
            operateLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            operateLog.setOperName(userName);
            operateLog.setOperTime(LocalDateTime.now());
            operateLog.setErrorMsg("");
            operateLog.setOperLocation("");
            if (e != null) {
                e.printStackTrace();
                operateLog.setStatus(Boolean.FALSE);
                operateLog.setErrorMsg(e.getClass().toString());
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operateLog.setMethod(className + "." + methodName + "()");
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operateLog, joinPoint);
        } catch (Exception exp) {
            log.error(" --log-- 操作日志异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param operateLog 操作日志
     * @param joinPoint
     * @throws Exception
     */
    public void getControllerMethodDescription(ApiOperation apiOperation, SysOperateLog operateLog, JoinPoint joinPoint) throws Exception {
        // 设置action动作
        // 设置标题
        operateLog.setTitle(StringUtils.hasLength(apiOperation.value()) ? apiOperation.value() : "");
        operateLog.setRequestType(apiOperation.requestType().name());
        if (apiOperation.enableRegion()) {
            operateLog.setOperLocation(IPAddressUtils.getAddress(operateLog.getOperIp()));
        }
        // 是否需要保存request，参数和值
        if (apiOperation.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(operateLog, joinPoint);
        }
//        this.applicationContext.publishEvent(operateLog);
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operateLog 操作日志
     * @param joinPoint
     * @throws Exception 异常
     */
    private void setRequestValue(SysOperateLog operateLog, JoinPoint joinPoint) throws Exception {
        MethodSignature signature = ((MethodSignature) joinPoint.getSignature());
        Method method = signature.getMethod();
        Parameter[] parameters = method.getParameters();
        Object[] args = joinPoint.getArgs();
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            Class<?> type = parameter.getType();
            if (!type.getName().equals("javax.servlet.http.HttpServletResponse") && !type.getName().equals("javax.servlet.http.HttpServletRequest")) {
                if (args[i] != null && (type.getName().equals("org.springframework.web.multipart.MultipartFile"))) {
                    MultipartFile file = (MultipartFile) args[i];
                    map.put(parameter.getName(), file.getOriginalFilename());
                } else  {
                    map.put(parameter.getName(), args[i] == null ? "" : args[i]);
                }
            }
        }
        operateLog.setOperParam(JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private ApiOperation getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            ApiOperation annotation = method.getAnnotation(ApiOperation.class);
            if (SwaggerPropertySetting.enableLog) {
                return annotation;
            } else {
                if (annotation.enableLog()) {
                    return annotation;
                }
            }
        }
        return null;
    }
}